﻿@using System.Globalization
@using Microsoft.Extensions.Options

@inject IOptions<RequestLocalizationOptions> LocalizationOptions
@inject LayoutService LayoutService
@inject IStringLocalizer<HeaderMenu> L
<MudTooltip Text="@CurrentLanguage">
    <MudMenu AnchorOrigin="Origin.BottomRight" TransformOrigin="Origin.TopRight" Class="mx-1" Icon="@Icons.Material.Outlined.Translate" Color="Color.Default" Dense="true">
        @if (SupportedLanguages is not null)
        {
            @foreach (var language in SupportedLanguages)
            {
                if (language.Name == CurrentLanguage)
                {
                    <MudMenuItem style="background:var(--mud-palette-primary); color:#FFF !important">@language.DisplayName</MudMenuItem>
                }
                else
                {
                    <MudMenuItem OnClick="() => ChangeLanguageAsync(language.Name)">@language.DisplayName</MudMenuItem>
                }
            }
        }
    </MudMenu>
</MudTooltip>

@code
{
    public string? CurrentLanguage { get; set; } = "en-US";
    public List<CultureInfo>? SupportedLanguages { get; set; } = new();

    protected override Task OnInitializedAsync()
    {
        SupportedLanguages = LocalizationOptions.Value.SupportedCultures?.ToList();
        CurrentLanguage = CultureInfo.CurrentCulture.Name;
        return Task.CompletedTask;
    }

    private async Task ChangeLanguageAsync(string languageCode)
    {
        CurrentLanguage = languageCode;
        Navigation.NavigateTo(Navigation.BaseUri + "?culture=" + languageCode, true);

        if (new CultureInfo(languageCode).TextInfo.IsRightToLeft)
            await LayoutService.SetRightToLeft();
        else
            await LayoutService.SetLeftToRight();

        await Task.CompletedTask;
    }
}